<template>
  <div
    v-loading="loading"
    element-loading-text="拼命加载中..."
  >
    <el-form ref="form" :model="form" label-width="120px" class="dataForm" :rules="formRules">
      <el-row>
        <el-col v-if="outside" :span="24">
          <el-form-item :label="$t('选择公司')" prop="companyId">
            <el-select v-model="form.companyId" filterable :placeholder="$t('请选择')" @change="selectCompanyHandle">
              <el-option
                v-for="item in companyOptions"
                :key="item.id"
                :label="item.companyName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="quick" :span="24">
          <el-form-item :label="$t('选择项目')" prop="companyId">
            <el-select v-model="form.companyId" filterable :placeholder="$t('请选择')" @change="selectCompanyHandle">
              <el-option
                v-for="item in dealOptions"
                :key="item.id"
                :label="item.dealName"
                :value="item.companyId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="outside" :span="24">
          <el-form-item :label="$t('选择模板')">
            <el-select v-model="templateId" :placeholder="$t('选择模板')" @change="asyncCmyTemp">
              <el-option
                v-for="dict in sysPcwTypeOptions"
                :key="dict.id"
                :label="$t(dict.name)"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('年份')" prop="year">
            <DatePicker v-model="form.year" type="year" value-format="yyyy" :placeholder="$t('年份')" @change="validatePcwData" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('报告周期')" prop="type">
            <el-select v-model="form.type" :placeholder="$t('报告周期')" @change="validatePcwData">
              <el-option
                v-for="item in typeOptions"
                :key="item.dictValue"
                :value="item.dictValue"
                :label="$t(item.dictLabel)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('币种')" prop="currency">
            <dictSelect
              v-model="form.currency"
              :clearable="true"
              dictionary="currency"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('数据来源')" prop="dataSource">
            <el-select v-model="form.dataSource" :placeholder="$t('数据来源')" @change="validatePcwData">
              <el-option
                v-for="dict in dataSourceOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <i v-show="tipShow" class="el-icon-s-opportunity" style="color:#f39c12;font-size:16px" />
          <span v-show="tipShow" style="color:#f39c12">录入重复的年份，报告周期和数据来源时会覆盖之前的财务数据</span>
        </el-col>
      </el-row>
    </el-form>
    <!-- v-if="!outside || (outside && companyId && templateId)" -->
    <!-- type="flex" justify="space-between" -->
    <div slot="footer">
      <el-row :class="[quick ? 'quick' : '']">
        <el-col :span="8">
          <p>{{ $t('Excel固定模板') }}</p>
          <el-button type="primary" @click="uploadHandle('excel')"> {{ $t('Excel') }}</el-button>
        </el-col>
        <el-col :span="8">
          <p>{{ $t('手动录入') }}</p>
          <el-button type="primary" @click="uploadHandle('hand')"> {{ $t('手动录入') }}</el-button>
        </el-col>
        <el-col :span="8">
          <p>{{ $t('OCR识别') }}</p>
          <el-button type="primary" @click="uploadHandle('ocr')">{{ $t('PDF,Excel,图片') }}</el-button>
        </el-col>
      </el-row>
    </div>
    <!-- <div slot="footer" class="dialog-footer" style="text-align: right;margin-top: 20px;"> -->
    <!--保存，保存并启动流程，取消 三个按钮-->
    <!-- <SaveBtn has-permi="company:pcw" :save-btn-name="$t('确定')" :save-show="!outside || !!(outside && companyId && templateId)" />
    </div> -->

    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="30%"
      :close-on-click-modal="false"
      :lock-scroll="false"
      append-to-body
    >
      <div v-loading="upload.loading">
        <el-upload
          ref="upload"
          class="upload-demo"
          drag
          :http-request="uploadType !== 'ocr' ? undefined : httpRequest"
          :headers="upload.headers"
          :action="upload.url"
          :show-file-list="true"
          :disabled="upload.loading"
          :multiple="upload.multiple"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :on-exceed="handleFileExceed"
          :on-change="onChange"
          :on-remove="onRemove"
          :auto-upload="false"
          :file-list="upload.fileList"
          :limit="upload.limit"
          :accept="upload.accept"
          :data="{ 'startPage': (upload.startPage ? upload.startPage : '0'), 'endPage': upload.endPage ? upload.endPage : '0' }"
          style="color: #1890ff;"
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">
            {{ $t('将文件拖到此处，或') }}
            <em>{{ $t('上传') }}</em>
          </div>
          <div slot="tip" class="el-upload__tip" style="color:red">
            {{ $t(upload.tip) }}
            <el-link v-if="!upload.pageHidden" type="primary" style="font-size:12px" @click="fetchTemplate">
              {{ $t('下载模板') }}
            </el-link>
          </div>
        </el-upload>
        <el-form v-if="upload.pageHidden" ref="uploadForm" :model="upload" label-width="120px" class="dataForm">
          <el-row>
            <el-col :span="24">
              <el-form-item prop="startPage" :rules="[{ required: true, message: $t('起始页不能为空'), trigger: 'blur' }]">
                <span slot="label">
                  {{ $t('PDF起始页') }}
                  <el-tooltip placement="top">
                    <div slot="content">
                      <span v-html="$t('识别起始页和结束页区间的PDF页面；<br>')" />
                      <span v-html="$t('1.不输入全部识别；<br>')" />
                      <span v-html="$t('2.只输入起始页, 从起始页开始识别至文档末；<br>')" />
                      <span v-html="$t('3.只输入结束页, 从第一页开始识别至结束页；<br>')" />
                    </div>
                    <i class="el-icon-question" style="margin-top: 10px; margin-right: 10px;" />
                  </el-tooltip>
                </span>
                <el-input-number v-model="upload.startPage" :min="1" :max="999" :placeholder="$t('从N页开始')" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item :label="$t('PDF结束页')" prop="endPage" :rules="[{ required: true, validator: checkPage, trigger: 'blur' }]">
                <el-input-number v-model="upload.endPage" :min="1" :max="999" :placeholder="$t('N页结束')" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer" style="text-align: right;">
          <el-button size="small" @click="upload.open = false">{{ $t('取消') }}</el-button>
          <el-button size="small" type="primary" @click="submitFileForm">{{ $t('上传') }}</el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="open"
      :close-on-click-modal="false"
      :lock-scroll="false"
      append-to-body
      :show-close="false"
      custom-class="pcwDialog"
    >
      <pcw-data-main-tab ref="pcwDataMainTab" :upload-data="responseData" :company-id="companyId" @cancel="open = false" @save="tipSave" />
    </el-dialog>
    <el-dialog
      v-if="handOpen"
      :visible.sync="handOpen"
      :close-on-click-modal="false"
      :lock-scroll="false"
      append-to-body
      :show-close="false"
      top="50px"
      width="70%"
    >
      <handUpload ref="HandUpload" :company-id="companyId" :upload-data="{}" :is-add="handOpenAdd" @save="tipSave" />
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { config } from '@/utils'
import { saveUpload, uploadFile, validatePcwData, saveUploadByHand, findAllDealBase } from '@/api/company/pcw/pcwDataMain'
import PcwDataMainTab from '@/views/company/pcw/pcwDataMainTab'
import HandUpload from '@/views/company/pcw/handUpload'
import { getConfigKey } from '@/api/system/config'
import { dealListPcwSysType } from '@/api/company/pcw/pcwSysType'
import { asyncCmyTemp } from '@/api/company/pcw/pcwCmyInit'
import { listCompanyBase } from '@/api/company/base/companyBase'

export default {
  name: 'PcwDataMainUpload',
  components: { PcwDataMainTab, HandUpload },
  props: {
    outside: {
      type: Boolean,
      default: false,
      desc: '是否外部调用'
    },
    companyId: {
      type: String,
      default: undefined
    }
  },
  data() {
    return {
      quick: this.outside, // 快捷添加标识
      tipShow: false,
      form: {
        year: '',
        type: undefined,
        dataSource: 'act',
        currency: 'CNY',
        companyId: undefined
      },
      upload: {
        open: false,
        loading: false,
        fileList: [],
        // 弹出层标题（项目导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: '',
        startPage: undefined,
        endPage: undefined,
        pageHidden: true,
        accept: '.xls, .xlsx',
        tip: '',
        multiple: false,
        limit: 5
      },
      open: false,
      base64: '',
      responseData: {},
      queryParams: {
      },
      loading: false,
      formRules: {
        year: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ],
        type: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ],
        dataSource: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ],
        currency: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ],
        companyId: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ]
      },
      typeOptions: [],
      sysPcwTypeOptions: [],
      templateId: undefined,
      companyOptions: [],
      dealOptions: [],
      dataSourceOptions: [],
      uploadType: '',
      formData: '',
      handOpen: false,
      handOpenAdd: false, // 新增标识
      sheetDataObject: {}
    }
  },
  created() {
    // 财务数据报告周期
    this.getDicts('financial_type').then(response => {
      this.typeOptions = response.data
    })
    this.getDicts('pcw_data_source').then(response => {
      this.dataSourceOptions = response.data
    })
  },
  mounted() {
     this.quick = this.getQuick()
     this.init()
  },
  methods: {
    init() {
      if (this.outside) {
        this.templateId = undefined
        this.sysPcwTypeOptions = []
        listCompanyBase({}).then(response => {
          this.companyOptions = response.rows
        })
      }
      if (this.quick) {
         this.templateId = undefined
        this.sysPcwTypeOptions = []
        // 查询项目
        findAllDealBase().then(response => {
          this.dealOptions = response.data
        })
      }
      this.tipShow = false
      delete this.form.sheetData
      this.responseData = {}
      this.upload.fileList = []
      this.upload.startPage = undefined
      this.upload.endPage = undefined
      this.loading = false
      this.$refs.form.resetFields()
    },
    // 文件上传中处理
    handleFileUploadProgress() {
      this.upload.loading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response) {
      this.upload.open = false
      this.upload.loading = false
      this.$refs.upload.clearFiles()
      if (response.code === 200) {
        this.msgSuccess(this.$t('导入成功'))
        this.open = true
        this.responseData = response.data
        this.$nextTick(() => {
          this.$refs.pcwDataMainTab.init()
        })
      } else if (response.code === 500) {
        this.msgError(response.msg)
      } else {
        this.$alert(response.msg, this.$t('导入结果'), { dangerouslyUseHTMLString: true })
      }
      // this.$alert(response.msg, '导入结果', { dangerouslyUseHTMLString: true })
    },
    // 提交上传文件
    submitFileForm() {
      let flag = true
      if (this.$refs.upload.uploadFiles.length === 0) {
        this.msgWarning(this.$t('请至少上传一个文件'))
        return false
      }
      if (this.upload.pageHidden) {
        this.$refs.uploadForm.validate(valid => {
          if (valid) {
            if (this.uploadType === 'ocr') {
              this.formData = new FormData()
            }
            this.$refs.upload.submit()
          } else {
            flag = false
            return false
          }
        })
      } else {
        if (this.uploadType === 'ocr') {
          this.formData = new FormData()
        }
        this.$refs.upload.submit()
      }
      if (!flag) {
        return false
      }
      if (this.uploadType === 'ocr') {
        this.upload.loading = true
        if (this.upload.startPage && this.upload.endPage) {
          this.formData.append('startPage', this.upload.startPage)
          this.formData.append('endPage', this.upload.endPage)
        }
        this.formData.append('companyId', this.companyId)
        uploadFile(this.formData).then(res => {
          this.handleFileSuccess(res)
        }).catch(() => {
          this.upload.loading = false
        })
      }
    },
    onChange(file, fileList) {
      if (file.raw.type.indexOf('image') !== -1 || file.name.toLowerCase().indexOf('xlsx') !== -1 || file.name.toLowerCase().indexOf('xls') !== -1 || fileList.length > 1) {
        this.upload.pageHidden = false
      } else {
        this.upload.pageHidden = true
      }
    },
    // 文件达到上限处理
    handleFileExceed() {
      this.msgError(this.$t('最多可上传' + this.upload.limit + '个文件'))
      // this.msgError(this.$t('最多可上传{limit}个文件', { limit: this.upload.limit }))
    },
    checkPage(rule, value, callback) {
      if (!this.upload.endPage) {
        callback(this.$t('结束页不能为空'))
      } else {
        if (this.upload.startPage > this.upload.endPage) {
          callback(new Error(this.$t('结束页不能大于起始页')))
        }
        callback()
      }
    },
    uploadHandle(type) {
      // 上传时校验表单信息
         this.$refs['form'].validate(valid => {
          console.log(this.form, this.$refs.form)
          if (valid) {
               this.upload.fileList = []
                if (type === 'excel') {
                  this.uploadType = 'excel'
                  this.upload.title = this.$t('Excel上传')
                  this.upload.pageHidden = false
                  this.upload.accept = '.xls, .xlsx'
                  this.upload.tip = '提示：仅支持Excel文件'
                  this.upload.limit = 1
                  this.upload.multiple = false
                  this.upload.url = config.baseURL + '/pcw/pcwDataMain/upload/pcwExcelData/' + this.companyId
                  this.upload.startPage = undefined
                  this.upload.endPage = undefined
                  this.upload.open = true
                } else if (type === 'ocr') {
                  this.uploadType = 'ocr'
                  this.upload.title = this.$t('OCR上传')
                  this.upload.pageHidden = true
                  this.upload.accept = '.xls, .xlsx, .pdf, image/*'
                  this.upload.tip = '提示：支持图片、PDF、Excel文件'
                  this.upload.limit = 5
                  this.upload.multiple = true
                  this.upload.url = config.baseURL + '/pcw/pcwDataMain/upload/pcwReportIdentify/' + this.companyId
                  this.upload.startPage = undefined
                  this.upload.endPage = undefined
                  this.upload.open = true
                } else if (type === 'hand') {
                  this.uploadType = 'hand'
                  this.handOpen = true
                  this.handOpenAdd = true
                }
          } else {
              this.msgError(this.$t('请先填写表单信息!'))
              return false
          }
        })
    },
    // 验证同一公司下面，不能出现同一年度+同一报告周期的财务报表
    validatePcwData() {
      if (this.form.year && this.form.year !== '' && this.form.type && this.form.type !== '' && this.form.dataSource) {
        this.$nextTick(() => {
          validatePcwData({ year: this.form.year, type: this.form.type, companyId: this.companyId, dataSource: this.form.dataSource }).then(res => {
            if (res.data === null) {
                this.tipShow = true
            } else {
                this.tipShow = false
            }
          }).catch(() => {
            this.$set(this.form, 'type', undefined)
          })
        })
      }
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      this.$parent.$parent.reset()
    },
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.loading = true
          this.form.uploadType = this.uploadType
                if (this.uploadType !== 'hand') {
                    this.form.companyId = this.companyId
                    this.form.sheetData = this.responseData
                    this.form.unit = this.responseData.unit
                    if (!this.form.sheetData) {
                    this.msgError(this.$t('请先上传数据'))
                    return false
                  }
                saveUpload(this.form).then(response => {
                this.loading = false
                if (response.code === 200) {
                  this.msgSuccess(this.$t('保存成功'))
                  this.$nextTick(() => {
                    this.$emit('refresh')
                  })
                } else {
                  this.msgError(response.msg)
                }
              }).catch(() => {
                this.loading = false
              })
          } else {
              // 手动录入
              this.form.companyId = this.companyId
              this.form.sheetData = this.sheetDataObject
              this.loading = true
              saveUploadByHand(this.form).then(response => {
                  this.loading = false
                  if (response.code === 200) {
                    this.msgSuccess(this.$t('保存成功'))
                    this.handOpen = false
                    this.$nextTick(() => {
                      this.$emit('refresh')
                    })
                  } else {
                    this.msgError(response.msg)
                  }
              }).catch(() => {
                this.loading = false
              })
            // console.log('手动录入')
          }
        }
      })
    },
    // 下载模板
    fetchTemplate() {
      var href1 = window.location.href
      var href2 = this.$route.path
      var url = href1.substring(0, href1.indexOf(href2))
      getConfigKey('download_default_template').then(res => {
        debugger
        if (res.msg === 'true') {
          this.downLoadExcel('/pcw/pcwTempSubject/export/', { companyId: this.companyId })
        } else {
          window.location.href = url + '/template/' + res.msg
        }
      })
    },
    // 同步当前公司的财务模板
    asyncCmyTemp(val) {
      this.loading = true
      asyncCmyTemp({ companyId: this.companyId, typeId: val }).then(res => {
        if (res.code === 200) {
          this.msgSuccess(this.$t('初始化模板成功'))
          this.loading = false
        }
      })
    },
    selectCompanyHandle(val) {
      this.companyId = val
      dealListPcwSysType({ companyId: val }).then(res => {
        this.sysPcwTypeOptions = res.rows
      })
    },
    httpRequest(file) {
      this.formData.append('file', file.file)
    },
    onRemove(file, fileList) {
      if (this.uploadType === 'ocr' && (fileList.length === 0) || (fileList.length === 1 && fileList[0].name.indexOf('pdf') !== -1)) {
        this.upload.pageHidden = true
      }
    },
    tipSave(sheetData) {
      // this.uploadType = uploadType
      this.sheetDataObject = sheetData
      this.submitForm()
      this.open = false
    },
     getQuick() {
      let quick = false
      if (this.$attrs.parameter && this.$attrs.parameter.quick) {
        quick = this.$attrs.parameter.quick
      }
      return quick
    },
    initialAssignment(data) {
      if (data) {
        this.form.year = data.year
        this.form.type = data.type
        this.form.dataSource = data.dataSource
      }
    }
  }
}
</script>

<style scoped lang="scss">
.upload-demo /deep/ .el-upload-list {
  height: auto;
}
.quick {
  position: absolute !important;
  bottom: 0 !important;
  width: 100%;
}
// /deep/ .el-dialog__header {
//   display: none !important;
//   padding: 0px !important;
//   padding-bottom: 0px !important;
// }
/deep/.previewDialog {
    top: 0px !important;
    width: 100%;
    margin-top: unset !important;
    padding: 30px;
    padding-top: 15px;
}
/deep/.el-upload-list__item-name{
  margin-right: 110px;
}
</style>
